<template>
  <div ref="chartContainer" style="width: 600px; height: 400px"></div>
</template>

<script setup>
import { ref, watch } from "vue";
import * as echarts from "echarts";
// import chinaJson from "echarts-map-json/china";
import chinaJson from "@/assets/china.json";
echarts.registerMap("china", chinaJson);

const chartContainer = ref(null);

watch(chartContainer, (newValue) => {
  if (newValue) {
    const myChart = echarts.init(newValue);

    const option = {
      custom: {
        renderItem: function (params, api) {
          const ctx = api.context;
          // const { width, height } = api.size;
          const lonStep = 30;
          const latStep = 30;
          const geoCoordSys = api.getCoorsys("geo"); // 获取地理坐标系

          // 绘制经线
          for (let lon = -180; lon <= 180; lon += lonStep) {
            const [x1, y1] = (geoCoordSys && geoCoordSys.coord([lon, -90])) || [
              0, 0,
            ];
            const [x2, y2] = (geoCoordSys && geoCoordSys.coord([lon, 90])) || [
              0, 0,
            ];
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.stroke();
          }

          // 绘制纬线
          for (let lat = -90; lat <= 90; lat += latStep) {
            const [x1, y1] = (geoCoordSys &&
              geoCoordSys.coord([-180, lat])) || [0, 0];
            const [x2, y2] = (geoCoordSys && geoCoordSys.coord([180, lat])) || [
              0, 0,
            ];
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.strokeStyle = "red";
            ctx.lineWidth = 1;
            ctx.stroke();
          }

          return {};
        },
        data: [],
      },
      title: {
        text: "经纬度网格示例",
      },
      geo: {
        type: "geo",
        map: "china",
      },
    };

    myChart.setOption(option);
  }
});
</script>

<style scoped></style>
